package com.tcwlkj.uuService.ui;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tcwlkj.uuService.MainActivity;
import com.tcwlkj.uuService.MyApp;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.HttpIp;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.UpDateVersionModel;
import com.tcwlkj.uuService.model.checkModel;
import com.tcwlkj.uuService.ui.login.LoginActivity;
import com.tcwlkj.uuService.ui.login.WelcomeActivity;
import com.tcwlkj.uuService.ui.set.BankActivity;
import com.tcwlkj.uuService.ui.set.ChangePassWordActivity;
import com.tcwlkj.uuService.update.DownLoadService;
import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.CommomDialog;
import com.tcwlkj.uuService.utils.Const;
import com.tcwlkj.uuService.utils.DataCleanManager;
import com.tcwlkj.uuService.utils.FileCacheUtils;
import com.tcwlkj.uuService.utils.MyDialog;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.utils.Tools;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/9/30 0030.
 */

public class SettingActivity extends BaseActivity {

    //银行卡设置
    @Bind(R.id.lay_bankcard_set)
    LinearLayout lay_BankCard_set;
    //关于我们
    @Bind(R.id.lay_aboutus_set)
    LinearLayout layAboutusSet;
    //清除缓存
    @Bind(R.id.lay_clearcache_set)
    LinearLayout layClearcacheSet;
    //    版本
    @Bind(R.id.lay_version_set)
    LinearLayout layVersionSet;
    //  退出登录
    @Bind(R.id.btn_exit_login)
    Button btnExitLogin;
    //  修改密码
    @Bind(R.id.lay_changps_set)
    LinearLayout layChangpsSet;
    //缓存大小
    @Bind(R.id.tv_clear_set)
    TextView tvClearSet;
    //当前版本
    @Bind(R.id.tv_version_set)
    TextView tvVersionSet;

    @Bind(R.id.lay_cancle_set)
    LinearLayout lay_cancle_set;

    private ProgressDialog progressDialog;
    private Intent updateService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        changeTitle("系统设置");
        Const.setting=this;
        tvVersionSet.setText(Tools.getVersion(baseContext));
        try {
            tvClearSet.setText(DataCleanManager.getTotalCacheSize(SettingActivity.this));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.lay_changps_set, R.id.lay_bankcard_set, R.id.lay_cancle_set,R.id.lay_aboutus_set, R.id.lay_version_set, R.id.btn_exit_login, R.id.lay_clearcache_set})
    public void onClick(View v) {
        Intent intent = null;
        super.onClick(v);
        switch (v.getId()) {
            case R.id.lay_changps_set:
                startActivity(ChangePassWordActivity.class);
                break;
            case R.id.lay_bankcard_set:
                startActivity(BankActivity.class);
                break;
            case R.id.lay_cancle_set://申请解约
                MyDialog myDialog = new MyDialog(SettingActivity.this, "CANCLE");
                myDialog.show();
                myDialog.setEditextHeight();
                myDialog.setClicklistener(new MyDialog.ClickListenerInterface() {
                    @Override
                    public void doConfirm(String msg) {
                        myDialog.dismiss();
                        if(TextUtils.isEmpty(msg)){
                            ToastUtil.getInstance().show("登录密码不能为空");
                            return;
                        }
                        Call<CommonResponse> httpResultCall = RetrofitUtils.getRequest(SettingActivity.this, false).chpass(PreferencesUtils.getString(MyApp.getContext(), "userID"),msg);
                        httpResultCall.enqueue(new HttpCallBack<CommonResponse>() {
                            @Override
                            public void onSuccess(Object t) {
                                MyDialog myDialog = new MyDialog(SettingActivity.this, "CANCLE");
                                myDialog.show();
                                myDialog.setText("您确定申请解约吗？\n通过审核后将永远无法\n使用同城跑男接单");
                                myDialog.setEditext();
                                myDialog.setClicklistener(new MyDialog.ClickListenerInterface() {
                                    @Override
                                    public void doConfirm(String msg) {
                                        myDialog.dismiss();
                                        if(TextUtils.isEmpty(msg)){
                                            ToastUtil.getInstance().show("请输入解约原因...");
                                            return;
                                        }
                                        termin(msg);
                                    }
                                    @Override
                                    public void doCancel() {
                                        myDialog.dismiss();
                                    }
                                });
                            }

                            @Override
                            public void onFail(int code, String message) {
                                ToastUtil.getInstance().show(message);
                            }
                        });

                    }
                    @Override
                    public void doCancel() {
                        myDialog.dismiss();
                    }
                });
                break;
            case R.id.lay_aboutus_set:
                intent = new Intent(baseContext, UserXieYi.class);
                intent.putExtra("XIEYI_TYPE", "5");
                startActivity(intent);
                break;
            case R.id.lay_version_set:
                Call<CommonResponse<checkModel>> httpResultCall = RetrofitUtils.getRequest(baseContext,false).check("13", "10",Tools.getVersion(baseContext));
                httpResultCall.enqueue(new HttpCallBack<CommonResponse<checkModel>>() {
                    @Override
                    public void onSuccess(Object t) {
                        CommonResponse commonResponse= (CommonResponse) t;
                        checkModel check= (checkModel) commonResponse.getData();
                        if(check.getForce().equals("0")){//自主更新
                            version(check.getVersion(),check.getUpNote(),check.getDownLink());//版本升级
                        }else {//强制更新
                            version(check.getVersion(),check.getUpNote(),check.getDownLink());//版本升级
                        }
                    }

                    @Override
                    public void onFail(int code, String message) {
                        ToastUtil.getInstance().show(message);
                    }
                });
                break;
            case R.id.lay_clearcache_set:
                clear();//清除缓存
                break;
            case R.id.btn_exit_login:
                Dialog();//退出
                break;
        }
    }

    private boolean isBound = false;
    private void version(String version,String upNote,String DownLink) {
        new CommomDialog(baseContext, R.style.dialog, "最新版本：V " + version+"\n"+upNote, new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        updateService = new Intent(SettingActivity.this, DownLoadService.class);
                        updateService.putExtra("url", DownLink);
                        isBound=bindService(updateService,conn, Context.BIND_AUTO_CREATE);
                        startService(updateService);
                        initProgress();
                    }
                }, R.string.address, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
        }).setTitle("版本升级").show();
    }

    ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个MsgService对象
            DownLoadService downLoadService = ((DownLoadService.MsgBinder)service).getService();
            downLoadService.setOnProgressListener(new DownLoadService.OnProgressListener() {
                @Override
                public void onProgress(int progress) {
                    progressDialog.setProgress(progress);
                }
                @Override
                public void cancleProgress() {
                    progressDialog.dismiss();
                    finish();
                }
            });
        }
    };
    public void initProgress(){
        progressDialog = new ProgressDialog(SettingActivity.this);
        progressDialog.setTitle("正在下载...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
    }

    private void clear() {
        new CommomDialog(baseContext, R.style.dialog, "确定要清除缓存吗?", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                DataCleanManager.clearAllCache(SettingActivity.this);
                try {
                    tvClearSet.setText(DataCleanManager.getTotalCacheSize(SettingActivity.this));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).setTitle("清除缓存").show();
    }

    public void Dialog() {
        new CommomDialog(baseContext, R.style.dialog, "确定要退出登录吗?", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if(!PreferencesUtils.getString(MyApp.getContext(),"oridIdList").equals("")){
                    ToastUtil.getInstance().show("您有未完成的订单，请先去完成");
                }else {
                    logout();
                    ChcheUtils.getInstance().setChche();
                    PreferencesUtils.putBoolean(MyApp.getContext(), "Login", false);
                    startActivity(LoginActivity.class);
                    JPushInterface.stopPush(MyApp.getContext());
                    finish();
                    Const.main.finish();
                }
            }
        }).setTitle("").show();
    }
    private void logout() {
        Call<CommonResponse<Object>> httpResultCall = RetrofitUtils.getRequest(SettingActivity.this, false).logout("10002",PreferencesUtils.getString(MyApp.getContext(), "userID"));
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<Object>>() {
            @Override
            public void onSuccess(Object t) {
            }
            @Override
            public void onFail(int code, String message) {

            }
        });
    }

    //解约
    private void termin(String msg){
        Log.d("userID",PreferencesUtils.getString(MyApp.getContext(), "userID"));
        Call<CommonResponse> httpResultCall = RetrofitUtils.getRequest(SettingActivity.this, false).termin(PreferencesUtils.getString(MyApp.getContext(), "userID"),msg);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse commonResponse= (CommonResponse) t;
                ToastUtil.getInstance().show(commonResponse.getMessage());
            }
            @Override
            public void onFail(int code, String message) {
                ToastUtil.getInstance().show(message);
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if(isBound){
            unbindService(conn);
            stopService(updateService);
            isBound=false;
        }
    }
}
